package com.dxg.msns.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dxg.msns.common.pojo.PageResult;
import com.dxg.msns.common.util.CodecUtils;
import com.dxg.msns.common.util.NumberUtils;
import com.dxg.msns.common.util.UUIDUtils;
import com.dxg.msns.common.util.UnderlineHump;
import com.dxg.msns.user.enums.UserRoleEnum;
import com.dxg.msns.user.mapper.UserMapper;
import com.dxg.msns.user.pojo.User;
import com.dxg.msns.user.service.UserService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    /**
     * 分页查询用户
     *
     * @param key
     * @param page
     * @param rows
     * @param sortBy
     * @param desc
     * @param
     * @return
     */
    @Override
    public PageResult<User> queryUsersByPage(String key, Integer page, Integer rows, String[] sortBy, Boolean[] desc,
            String[] uids) {
        // Example example = new Example(User.class);
        // Example.Criteria criteria = example.createCriteria();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // if (isAll) {
        // queryWrapper.ne("status", "-1");
        // } else {
        // queryWrapper.eq("status", "-1");
        // }

        if (StringUtils.isNotBlank(key)) {
            // criteria.andLike("uname", "%" + key + "%");
            queryWrapper.like("uname", key);
        }
        if (ArrayUtils.isNotEmpty(uids)) {
            // criteria.andIn("uid", Arrays.asList(uids));
            queryWrapper.in("uid", Arrays.asList(uids));
        }

        // 添加排序条件
        if (ArrayUtils.isNotEmpty(sortBy) && desc != null) {
            // example.setOrderByClause(UnderlineHump.HumpToUnderline(sortBy[0]) + " " +
            // (desc[0] ? "desc" : "asc"));
            String orderColumn = UnderlineHump.HumpToUnderline(sortBy[0]);
            if (desc[0]) {
                queryWrapper.orderByDesc(orderColumn);
            } else {
                queryWrapper.orderByAsc(orderColumn);
            }
        }

        // 创建分页对象
        Page<User> pageObj = new Page<>(page, rows);
        // 执行分页查询
        IPage<User> userPage = userMapper.selectPage(pageObj, queryWrapper);

        List<User> users = userPage.getRecords();
        if (ArrayUtils.isNotEmpty(uids)) {
            for (User user : users) {
                user.setEmail(null);
                user.setBirthday(null);
                user.setPhone(null);
                user.setUpassword(null);
                user.setSalt(null);
            }
        }
        System.out.println(users);

        return new PageResult<>(userPage.getTotal(), users);
    }

    /**
     * 根据用户名查询用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean findUserByName(User user) {
        if (user == null || user.getUname() == null) {
            throw new RuntimeException("用户信息传递有误");
        }
        // 使用MyBatis-Plus的QueryWrapper查询
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uname", user.getUname());
        Integer count = userMapper.selectCount(queryWrapper);
        return count == 0;
    }

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    @Transient
    @PostMapping("/register")
    public void saveUser(User user) {
        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        // 加密密码
        if (user.getUpassword() != null && !user.getUpassword().isEmpty()) {
            user.setUpassword(CodecUtils.md5Hex(user.getUpassword(), salt));
        }
        user.setUid(UUID.randomUUID().toString().replace("-", "").toLowerCase());
        user.setStatus("1"); // 用户状态：1-正常，0-禁用

        // 设置用户角色：如果没有指定角色，默认为普通用户
        if (user.getIsSinger() == null) {
            user.setUserRole(UserRoleEnum.NORMAL_USER);
        }

        // userMapper.insertSelective(user);
        userMapper.insert(user);
    }

    /**
     * 修改用户
     *
     * @param user
     */
    @Override
    @Transient
    public void updateUser(User user) {
        // 如果密码不为空，则重新加密密码
        if (user.getUpassword() != null && !user.getUpassword().isEmpty()) {
            // 生成新的盐
            String salt = CodecUtils.generateSalt();
            user.setSalt(salt);
            // 加密密码
            user.setUpassword(CodecUtils.md5Hex(user.getUpassword(), salt));
        }
        // Example example = new Example(User.class);
        // Example.Criteria criteria = example.createCriteria();
        // criteria.andEqualTo("id", user.getId());
        // userMapper.updateByExampleSelective(user, example);
        userMapper.updateById(user);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Transient
    @Override
    public void deleteUser(Integer id){
        userMapper.deleteById(id);
    }

    /**
     * 查询用户数据是否可用
     *
     * @param data
     * @param type
     * @return
     */
    @Override
    public Boolean checkUserData(String data, Integer type) {
        // User user = new User();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        switch (type) {
            case 1:
                // user.setUname(data);
                queryWrapper.eq("uname", data);
                break;
            case 2:
                // user.setPhone(data);
                queryWrapper.eq("phone", data);
                break;
            case 3:
                // user.setEmail(data);
                queryWrapper.eq("email", data);
                break;
            default:
                return null;
        }
        // return userMapper.selectCount(user) == 0;
        return userMapper.selectCount(queryWrapper) == 0;
    }

    /**
     * 根据id查找用户
     *
     * @param uid
     * @return
     */
    @Override
    public User queryNameAvatarById(String uid) {
        return userMapper.queryNameAvatarById(uid);
    }

    @Override
    public Boolean sendVerifyCode(String email) {
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        try {
            Map<String, String> msg = new HashMap<>();
            msg.put("email", email);
            msg.put("code", code);
            this.amqpTemplate.convertAndSend("msns.sms.email.exchange", "sms.verify.code", msg);
            this.redisTemplate.opsForValue().set(email, code);
            this.redisTemplate.expire(email, 5, TimeUnit.MINUTES);
            return true;
        } catch (AmqpException e) {
            e.printStackTrace();
            System.out.println("baocuole");
            return false;
        }
    }

    @Override
    @Transient
    public Map<String, Object> register(User user, String code) {
        String codeCache = this.redisTemplate.opsForValue().get(user.getEmail());
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.equals(code, codeCache)) {
            map.put("boo", false);
            map.put("err", "验证码错误！");
            return map;
        }
        // 生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        // 加密密码
        user.setUpassword(CodecUtils.md5Hex(user.getUpassword(), salt));
        user.setId(null);
        user.setUid(UUIDUtils.getUUID());
        user.setStatus("1"); // 用户状态：1-正常，0-禁用

        // 设置用户角色：如果没有指定角色，默认为普通用户
        if (user.getIsSinger() == null) {
            user.setUserRole(UserRoleEnum.NORMAL_USER);
        }

        // boolean b = userMapper.insertSelective(user) == 1;
        boolean b = userMapper.insert(user) == 1;

        if (b) {
            // 注册成功删除redis中的记录
            this.redisTemplate.delete(user.getEmail());
        } else {
            map.put("err", "注册失败！");
        }
        map.put("boo", b);
        return map;
    }

    @Override
    public User queryUser(String uname, String upassword) {
        try {
            // 使用MyBatis-Plus的QueryWrapper方式查询，更安全可靠
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uname", uname);

            // 查询用户
            User user = this.userMapper.selectOne(queryWrapper);

            if (user == null) {
                System.out.println("User not found: " + uname);
                return null;
            }

            System.out.println("Found user: " + user);

            // 使用MD5进行密码比对
            String salt = user.getSalt();
            String encryptedPassword = CodecUtils.md5Hex(upassword, salt);

            if (!user.getUpassword().equals(encryptedPassword)) {
                System.out.println("Password mismatch for user: " + uname);
                return null;
            }

            System.out.println("User authentication successful: " + uname);
            return user;

        } catch (Exception e) {
            System.err.println("Error in queryUser: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据id查找用户
     *
     * @param id
     * @return
     */
    @Override
    public User queryById(Integer id) {
        // User record = new User();
        // record.setId(id);
        // User user = userMapper.selectOne(record);
        User user = userMapper.selectById(id);
        if (user == null) {
            return null;
        }
        return user;
    }

    /**
     * 修改密码
     *
     * @param id
     * @param newPwd
     */
    @Override
    @Transient
    public void changePwdById(Integer id, String newPwd) {
        try {
            // 生成盐
            String salt = CodecUtils.generateSalt();
            // 根据生成的盐进行加密
            newPwd = CodecUtils.md5Hex(newPwd, salt);
            userMapper.changePwdById(id, newPwd, salt);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改头像
     *
     * @param uid
     * @param avatarUrl
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeAvatar(Integer uid, String avatarUrl) {
        try {
            System.out.println("Service changeAvatar called with uid: " + uid + ", avatarUrl: " + avatarUrl);
            // 将Integer类型的uid转换为String类型
            userMapper.changeAvatarByUid(String.valueOf(uid), avatarUrl);
            System.out.println("Service changeAvatar completed successfully");
        } catch (Exception e) {
            System.err.println("Error in changeAvatar: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据uid查找用户
     *
     * @param uid
     * @return
     */
    @Override
    public User queryByUid(String uid) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);
            return userMapper.selectOne(queryWrapper);
        } catch (Exception e) {
            System.err.println("根据uid查询用户异常：" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据uid修改密码
     *
     * @param uid
     * @param newPassword
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changePwdByUid(String uid, String newPassword) {
        try {
            // 根据uid查找用户
            User user = queryByUid(uid);
            if (user != null) {
                // 生成盐
                String salt = CodecUtils.generateSalt();
                // 根据生成的盐进行加密
                String encryptedPassword = CodecUtils.md5Hex(newPassword, salt);

                // 更新密码和盐值
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("uid", uid);

                User updateUser = new User();
                updateUser.setUpassword(encryptedPassword);
                updateUser.setSalt(salt);

                userMapper.update(updateUser, queryWrapper);
            }
        } catch (Exception e) {
            System.err.println("根据uid修改密码异常：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据uid修改头像
     *
     * @param uid
     * @param avatarUrl
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeAvatarByUid(String uid, String avatarUrl) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);

            User updateUser = new User();
            updateUser.setAvatarUrl(avatarUrl);

            userMapper.update(updateUser, queryWrapper);
            System.out.println("根据uid修改头像成功");
        } catch (Exception e) {
            System.err.println("根据uid修改头像异常：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据uid修改昵称
     *
     * @param uid
     * @param uname
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeNicknameByUid(String uid, String uname) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);

            User updateUser = new User();
            updateUser.setUname(uname);

            userMapper.update(updateUser, queryWrapper);
            System.out.println("根据uid修改昵称成功");
        } catch (Exception e) {
            System.err.println("根据uid修改昵称异常：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 根据uid修改用户角色
     *
     * @param uid
     * @param roleCode
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void changeRoleByUid(String uid, Integer roleCode) {
        try {
            // 验证角色代码是否有效
            if (!UserRoleEnum.isValidCode(roleCode)) {
                throw new IllegalArgumentException("无效的角色代码：" + roleCode);
            }

            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("uid", uid);

            User updateUser = new User();
            updateUser.setIsSinger(roleCode);

            userMapper.update(updateUser, queryWrapper);

            UserRoleEnum roleEnum = UserRoleEnum.getByCode(roleCode);
            System.out.println("根据uid修改用户角色成功：" + roleEnum.getDescription());
        } catch (Exception e) {
            System.err.println("根据uid修改用户角色异常：" + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }


    /**
     * 根据关键字进行模糊查询用户
     *
     * @param key 模糊查询关键字
     * @return 用户列表
     */
    @Override
    public List<User> queryUsersByName(String key) {
        // 调用Mapper的模糊查询方法
        return userMapper. queryUsersByName(key);
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateUserInfo(User user) {
        // 获取传入的 User 对象，根据 uid 查找现有用户信息
        User existingUser = userMapper.selectByUid(user.getUid());  // 使用自定义的查询方法，依据 uid 查找

        // 如果用户不存在，则抛出异常
        if (existingUser == null) {
            throw new RuntimeException("User not found!");
        }

        // 动态更新字段
        if (user.getUname() != null) {
            existingUser.setUname(user.getUname());
        }
        if (user.getEmail() != null) {
            existingUser.setEmail(user.getEmail());
        }
        if (user.getPhone() != null) {
            existingUser.setPhone(user.getPhone());
        }
        if (user.getSex() != null) {
            existingUser.setSex(user.getSex());
        }
        if (user.getBirthday() != null) {
            existingUser.setBirthday(user.getBirthday());
        }
        if (user.getAvatarUrl() != null) {
            existingUser.setAvatarUrl(user.getAvatarUrl());
        }
        if (user.getDescription() != null) {
            existingUser.setDescription(user.getDescription());
        }

        if (user.getIsSinger() != null) {
            existingUser.setIsSinger(user.getIsSinger());
        }

        // 执行更新
        userMapper.updateByUidSelective(existingUser);  // 使用自定义的更新方法，依据 uid 更新
    }





}
